package com.zxzhu.joyread.Model;

import android.graphics.Bitmap;
import android.os.Environment;
import android.util.Log;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.SignUpCallback;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.HashMap;

/**
 * Created by zia on 17-7-23.
 */

public class RegisterModel {

    private final static String TAG = "RegisterModelTest";

    public void registerWithLocalIcon(String username, String password, String nickname, String gender, String bitmapPath, SignUpCallback callback) {//还有一个回调参数
        AVUser user = new AVUser();
        user.setUsername(username);
        user.setPassword(password);
        user.put("nickname",nickname);
        user.put("gender",gender);
        AVFile avFile = null;
        try {
            if (bitmapPath != null)
            {
                avFile = AVFile.withAbsoluteLocalPath(username, bitmapPath);
                Log.d(TAG,"bitmap path:  "+bitmapPath);
            }
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
        if(avFile != null) user.put("head",avFile);
        user.signUpInBackground(callback);
        user.saveInBackground();
    }

    public void registerWithURL(String username, String password, String nickname, String gender, String bitmapPath, SignUpCallback callback){
        AVUser user = new AVUser();
        user.setUsername(username);
        user.setPassword(password);
        user.put("nickname",nickname);
        user.put("gender",gender);
        AVFile avFile = null;
        if (bitmapPath != null){
            avFile = new AVFile(username,bitmapPath,new HashMap<String, Object>());
            Log.d(TAG,"bitmap path:  "+bitmapPath);
        }
        if(avFile != null) user.put("head",avFile);
        user.signUpInBackground(callback);
        user.saveInBackground();
    }


    /**
     * 图像保存到文件中，并获取路径，等待上传
     * @param bitmap bitmap
     * @return 路径
     */
    public String saveBitmap(Bitmap bitmap){
        FileOutputStream foutput = null;
        String imagePath = null;
        try {
            File appDir = new File(Environment.getExternalStorageDirectory(), "joyRead");
            if (!appDir.exists()) {
                appDir.mkdir();
            }
            String fileName = "head.jpg";
            File file = new File(appDir, fileName);
            foutput = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, foutput);
            imagePath = file.getAbsolutePath();
            Log.d(TAG, "save image path:" + imagePath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return imagePath;
    }
}
